package main

import (
	pb "ihos/ihos"
	"log"
)

type denglu struct {
	id   int32  //PK
	jslx int32  //角色类型
	dlbz int32  //登录标志
	jsmc string //角色名称
	jsdw string //角色单位
	dlmc string //登录名称
	dljy string //登录密码
}

func (w *denglu) GetFromDB(id int32) error {
	sql := "SELECT id,jslx,dlbz,jsmc,jsdw,dlmc,dljy FROM denglu WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.jslx, &w.dlbz, &w.jsmc, &w.jsdw, &w.dlmc, &w.dljy)
}

func (w *denglu) GetByDlmc(dlmc string) error {
	sql := "SELECT id,jslx,dlbz,jsmc,jsdw,dlmc,dljy FROM denglu WHERE dlmc=$1"
	return DBConn.db.QueryRow(sql, dlmc).Scan(&w.id, &w.jslx, &w.dlbz, &w.jsmc, &w.jsdw, &w.dlmc, &w.dljy)
}

func (w *denglu) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE denglu set jslx=$1,dlbz=$2,jsmc=$3,jsdw=$4,dlmc=$5,dljy=$6 where id=$7 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.jslx, w.dlbz, w.jsmc, w.jsdw, w.dlmc, w.dljy, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO denglu(jslx,dlbz,jsmc,jsdw,dlmc,dljy) VALUES($1,$2,$3,$4,$5,$6) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.jslx, w.dlbz, w.jsmc, w.jsdw, w.dlmc, w.dljy).Scan(&w.id)
	}
	return err
}

//save data from protobuf
// func (w *denglu) Save(dlxx *pb.DengLuL2) error {
// 	w.fromPB(dlxx)
// 	if err := w.GetByDlmc(dlxx.GetDL().GetDLMC()); err != nil {
// 		//cannot found
// 	}
// 	return w.SaveToDB(w.id)
// }

// todo: add jslx check
func (w *denglu) Check(dlmc, dljy, jsdw string, jslx int32) int {
	log.Println("DengLu Check:", dlmc, dljy, jsdw, jslx)
	sql := "SELECT id,jslx,dlbz,jsmc,jsdw,dlmc,dljy FROM denglu WHERE dlmc=$1 AND dljy=$2 AND jsdw=$3 AND jslx=$4"
	// sql := "SELECT id,jslx,dlbz,jsmc,jsdw,dlmc,dljy FROM denglu WHERE dlmc='" + dlmc + "' AND dljy='" + dljy + "' AND jslx=" + fmt.Sprint(jslx)
	err := DBConn.db.QueryRow(sql, dlmc, dljy, jsdw, jslx).Scan(&w.id, &w.jslx, &w.dlbz, &w.jsmc, &w.jsdw, &w.dlmc, &w.dljy)
	log.Println(sql)
	if err != nil {
		sql = "SELECT id,jslx,dlbz,jsmc,jsdw,dlmc,dljy FROM denglu WHERE dlmc=$1"
		err = DBConn.db.QueryRow(sql, dlmc).Scan(&w.id, &w.jslx, &w.dlbz, &w.jsmc, &w.jsdw, &w.dlmc, &w.dljy)
		if err != nil {
			log.Println("Not exist")
			return 2 //account not exist
		} else {
			log.Println("Invalid pass")
			return 1 //account exist, but pass is wrong
		}
	}
	return 0
}

func (w *denglu) toPB() *pb.DengLuL2 {
	d := &pb.DengLuL2{
		JS: &pb.JiaoSeInfoL1{
			ID:   w.id,
			JSMC: w.jsmc,
			JSLX: pb.YHLX(w.jslx),
			JSDW: w.jsdw,
		},
		DL: &pb.DengLuInfoL1{
			DLMC: w.dlmc,
			BZ:   pb.DengLuInfoL1_DLBZ(w.dlbz),
		},
	}
	return d
}

func (w *denglu) fromPB(p *pb.DengLuL2) *denglu {
	//登录名称唯一，如果存在则读取记录，获得ID
	if err := w.GetByDlmc(p.GetDL().GetDLMC()); err != nil {
		w.id = 0
	}
	// w.id = p.GetJS().GetID()
	w.jslx = int32(p.GetJS().GetJSLX())
	w.dlbz = int32(p.GetDL().GetBZ())
	w.jsmc = p.GetJS().GetJSMC()
	w.jsdw = p.GetJS().GetJSDW()
	w.dlmc = p.GetDL().GetDLMC()
	w.dljy = p.GetDL().GetDLJY()
	return w
}
